<template>
  <div class="login_container">
    <el-row>
      <!-- :xs的值小于760px 左侧宽度为0 :span占比份数-->
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginForms"
        >
          <h1>Hello</h1>
          <h3>欢迎来到硅谷甄选</h3>
          <!-- prop:校验字段的名字 -->
          <el-form-item prop="username">
            <el-input
              placeholder="请输入用户名"
              :prefix-icon="User"
              v-model="loginForm.username"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              v-model="loginForm.password"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="submit"
              @click="loginBtn"
              :loading="loading"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from "@element-plus/icons-vue";
import { reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElNotification } from "element-plus";
//引入当前时间函数
import { getTime } from "@/utils/time";
//引入仓库
import useUserStore from "@/store/modules/user";
//引入type类型
import type { loginData } from "@/api/user/type";
import { defineOptions } from "vue";
defineOptions({
  name: "Login",
});
//获取路由器
let $router = useRouter();
let $route = useRoute();
//应用仓库
const useStore = useUserStore();
//收集表单数据
const loginForm = reactive<loginData>({
  username: "admin",
  password: "111111",
});
//登录按钮的加载效果
let loading = ref(false);
//获取el-form组件实例
let loginForms = ref();
// 自定义校验规则
const validateUsername = (rule: any, value: any, callback: any) => {
  const regex = /^[a-z]{5,}$/; // 正则表达式，匹配至少5个小写字母
  if (regex.test(value)) {
    callback();
  } else {
    callback("用户名必须只包含小写字母,并且长度至少为5个字符");
  }
};
const validatePassword = (rule: any, value: any, callback: any) => {
  const regex = /^\d{6,}$/; // 正则表达式，匹配至少6个数字
  if (regex.test(value)) {
    callback();
  } else {
    callback("密码长度为大等于6的数字");
  }
};
//规则对象属性:
/*
  required,代表这个字段务必要校验的
  min:文本长度至少多少位
  max:文本长度最多多少位
  message:错误的提示信息
  trigger:触发校验表单的时机 change->文本发生变化触发校验,blur:失去焦点的时候触发校验规则
*/
const rules = reactive({
  username: [
    // { required: true, min: 5, message: "账号长度必须为5位", tirgger: "blur" },
    // 自定义校验规则
    { required: true, validator: validateUsername, tirgger: "blur" },
  ],
  password: [
    // { required: true, min: 6, message: "密码长度必须为6位", tirgger: "blur" },
    // 自定义校验规则
    { required: true, validator: validatePassword, tirgger: "blur" },
  ],
});

//登录按钮
const loginBtn = async () => {
  //开始加载
  loading.value = true;
  //保证全部表单校验通过之后再发之后的请求
  try {
    await loginForms.value.validate();
  } catch {
    ElNotification({
      type: "error",
      message: "表单验证失败",
    });
    setTimeout(() => {
      loading.value = false;
    }, 1000);
    return;
  }

  useStore
    .userLogin(loginForm)
    .then(() => {
      loading.value = false;
      //判断路径中是否有参数 有参数往参数条转否则跳转到根路径下
      let redirect: any = $route.query.redirect;
      // console.log(redirect);
      //登录成功跳转页面
      $router.push({ path: redirect || "/" });
      //提示登录成功信息
      ElNotification({
        type: "success",
        message: "欢迎回来",
        title: `Hi!${getTime()}好`,
      });
    })
    .catch((error) => {
      loading.value = false;
      ElNotification({
        type: "error",
        message: (error as Error).message,
      });
    });
};
</script>

<style scoped lang="scss">
.login_container {
  width: 100vw;
  height: 100vh;
  background: url("@/assets/images/background.jpg");
  background-size: cover;
  .login_form {
    position: relative;
    top: 30vh;
    width: 80%;
    background: url("../../assets/images/login_form.png");
    background-size: cover;
    color: white;
    padding: 20px;
    h1 {
      font-size: 40px;
      font-weight: bold;
    }
    h3 {
      font-size: 20px;
      margin: 10px 0;
    }
    .submit {
      width: 100%;
    }
  }
}
</style>
